<?php
namespace api\common\model;
use think\Db;
class Appointment extends \think\Model //预约表
{
    protected $autoWriteTimestamp = true;
    protected $table = 'appointment';

    
    /**
     * 生成预约订单,时间,姓名,电话,地址,用户id
     */
    public function createOrder($data){
        $res = false;
        $date = getNowDate();
        $orderNumber = time().'3'.$data['userId'].random(2,1);//订单号
        $data['payStatus'] = 1;
        $data['addTime'] = $date;
        $data['updTime'] = $date;
        $xcxinfo = Config::get('xcxinfo');
        $data['money'] = $xcxinfo['appoint'];//预约服务费(不退)
        $data['orderNumber'] = $orderNumber;
        $insert = Db::name($this->table)->insert($data);
        if($insert){
            $res['orderNumber'] = $orderNumber;
        }
        return $res;
    }

    /**
     * 修改订单信息
     */
    public function updOrder($data,$orderNumber){
        $upd = Db::name($this->table)->where('orderNumber',$orderNumber)->update($data);
        return $upd;
    }

    /**
     * 根据订单号查看订单信息
     */
    public function order_info($orderNumber){
        $res =Db::name($this->table)->where('orderNumber',$orderNumber)->find();
        return $res;
    }


    /**
     * 修改预约订单支付状态
     */
    public function updPayStatus($orderNumber,$status,$wxorder,$payTime){
        $data['payStatus'] = $status;
        $data['wxOrder'] = $wxorder;
        $data['payTime'] = $payTime;
        $data['updTime'] = getNowDate();
        $transStatus = false;
        Db::startTrans();
        try{
            // 修改订单信息
            $orders = Db::name($this->table)->where('orderNumber', $orderNumber)->update($data);
            if(!$orders){
                throw new \Exception("订单状态修改失败");
            }
            $orderInfo = $this->order_info($orderNumber);
            // 生成上门订单
            $orderNumber_door = time().'2'.$orderInfo['userId'].random(2,1);//订单号
            $data_door['orderNumber'] = $orderNumber_door;
            $data_door['userId'] = $orderInfo['userId'];
            $data_door['type'] = 1;
            $data_door['status'] = 1;
            $data_door['userStatus'] = 2;
            $data_door['staffId'] = 0;
            $data_door['shopId'] = 0;
            $date = getNowDate();
            $data_door['addtime'] = $date;
            $data_door['updtime'] = $date;
            $data_door['payStatus'] = 1;
            $data_door['appointId'] = $orderInfo['appointId'];
            $doorOrder = Db::name('order')->insert($data_door);
            if(!$doorOrder){
                throw new \Exception("上门订单生成失败");
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $transStatus =  $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
        
    }
}
